import { Toast } from 'antd-mobile';

const domain = 'http://localhost:3001';

function urlencoded(data) {
    return Object.keys(data)
        .filter(key => data[key] !== undefined && data[key] !== null)
        .map(key => `${key}=${encodeURIComponent(data[key])}`).join('&')
}

export function Get(url, options) {
    const data = options && options.data || {};
    options && delete options.data;
    const query = urlencoded(data);
    // Toast.loading('loading', 0);
    return fetch(query ? `${domain}${url}?${query}` : `${domain}${url}`, Object.assign({
        method: 'get',
    }, options))
    .then(res => {
        Toast.hide();
        const data = res.json();
        if (data.redirect) {
            window.location.replace(data.redirect);
        }
        return data;
    });
}

export function Delete(url, options) {
    // Toast.loading('loading', 0);
    return fetch(`${url}`, Object.assign({
        method: 'delete',
        
    }, options))
    .then(res => {
        Toast.hide();
        const data = res.json();
        if (data.redirect) {
            window.location.replace(data.redirect);
        }
        return data;
    });
}

export function Post(url, data) {
    // Toast.loading('loading', 0);
    return fetch(`${domain}${url}`, Object.assign({
        method: 'post',
        
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        body: urlencoded(data)
    }))
    .then(res => {
        Toast.hide();
        const data = res.json();
        if (data.redirect) {
            window.location.replace(data.redirect);
        }
        return data;
    });
}

export function PostForm(url, datas) {
    // Toast.loading('loading', 0);
    const formData = new FormData();
    Object.keys(datas).filter(key => datas[key]).forEach(key => {
        formData.append(key, datas[key]);
    });
    return fetch(`${domain}${url}`, {
        method: 'post',
        
        body: formData
    })
    .then(res => {
        Toast.hide();
        const data = res.json();
        if (data.redirect) {
            window.location.replace(data.redirect);
        }
        return data;
    });
}

export function PostJson(url, datas) {
    // Toast.loading('loading', 0);
    return fetch(`${domain}${url}`, {
        method: 'post',
        
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(datas)
    })
    .then(res => { 
        Toast.hide();
        const data = res.json();
        if (data.redirect) {
            window.location.replace(data.redirect);
        }
        return data;
    });
}